package vip.ifmm.lehouse.user.service.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Red
 * email: 1318944013@qq.com
 * date: 2019/6/16 15:25
 */
@Component
@SuppressWarnings("unchecked")
public class RedisUtil {

    private static RedisTemplate redisTemplate;

    // 利用set方法注入静态属性
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    /**
     * redis set方法
     * @param key key值
     * @param value value值
     * @param timeout 过期时间 <=0 永不过期
     */
    public static void set(String key, Object value, long timeout) {
        if (timeout <= 0) {
            redisTemplate.opsForValue().set(key, value);
            return;
        }
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * redis get方法
     * @param key key值
     * @param clazz 转换成的对象
     * @param <T> 泛型
     * @return value值，可以转成指定的对象
     */
    public static <T> T get(String key, Class<T> clazz) {
        return (T) redisTemplate.opsForValue().get(key);
    }
}
